package sparseArray;

/**
 * 稀疏数组
 * 五子棋棋盘为例 节省空间
 */
public class sparseArrayDemo01 {
    public static void main(String[] args) {
        int chessArray[][] = new int[11][11];
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        for (int[] row : chessArray){
            for (int data:row){
                System.out.printf("%3d\t",data);
            }
            System.out.println();
        }
        int sum = 0;
        // 遍历
        for (int[] row : chessArray){
            for (int data:row){
                if (data!=0) sum++;
            }
        }
        System.out.println("==================");
        int sparse[][] = new int[sum+1][3];
        sparse[0][0] = 11;
        sparse[0][1] = 11;
        sparse[0][2] = sum;
        int count = 1;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j <11 ; j++) {
                if (chessArray[i][j]!=0){
                    sparse[count][0] = i;
                    sparse[count][1] = j;
                    sparse[count][2] = chessArray[i][j];
                    count++;
                }
            }
        }
        for (int[] row : sparse){
            for (int data:row){
                System.out.printf("%5d\t",data);
            }
            System.out.println();
        }
        System.out.println("数组===转换==》稀疏数组开始了");
        int chessArrays[][] = new int[sparse[0][0]][sparse[0][1]];
        int sums = sparse[0][2];
        for (int i = 1; i <= sums; i++) {
                chessArrays[sparse[i][0]][sparse[i][1]] = sparse[i][2];
        }
        for (int[] row : chessArrays){
            for (int data:row){
                System.out.printf("%5d\t",data);
            }
            System.out.println();
        }
    }
}
